package com.example.wendao.view.ui.fragment;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.common.PageUtils;
import com.example.wendao.model.entity.News;
import com.example.wendao.model.entity.User;
import com.example.wendao.model.service.NewsService;
import com.example.wendao.model.service.UserService;
import com.example.wendao.view.adapter.InfoAgreeListAdapter;
import com.example.wendao.viewmodel.UserViewModel;


/**
 * A simple {@link Fragment} subclass.
 */
public class InfomationAgreeNewsFragment extends Fragment {
    //private ActivityPagingTestBinding binding;
    private InfoAgreeListAdapter adapter = new InfoAgreeListAdapter();
    private UserViewModel userViewModel ;
    private String SQL = "";
    private User user;
    private int[] arr;
    private RecyclerView recyclerView;
    private LiveData<PagedList<User>> agrees;
    private UserService userService;


    public InfomationAgreeNewsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_infomation_agreenews, container, false);
        recyclerView=view.findViewById(R.id.rv_infoagreenews);
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
        user = userViewModel.getCurrentUser();
        NewsService newsService = new NewsService();
        News[] news = newsService.findAllNewsByAuthorIdInArray(user.getUserId());
        String[] s;
        int count=0;
        for(int i=0;i<news.length;i++){
            s=news[i].getNewsAgreeId().split(",");
            for(int j =0;j<s.length;j++){
                arr[count+j]=Integer.parseInt(s[j]);
            }
            count+=s.length;
        }
        //将arr数组中的id封装成一段sql语句
        if(arr.length > 0) {
            SQL += " '";
            for(int i=0; i<arr.length-1; i++) {
                SQL = SQL+ arr[i] + "','";
            }
            SQL += arr[arr.length-1] + "'";
        }
        userViewModel.findSomeUsersByUserIds(SQL).observe(this.getViewLifecycleOwner(), adapter::submitList);
        PageUtils.initRecyclerView(recyclerView, adapter, new LinearLayoutManager(this.getActivity()));

        return view;
    }

}
